import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:lepig/model/ProductInfoModel.dart';
import 'package:lepig/model/ProductModel.dart';
import 'package:lepig/request/HttpUrlProductDetails.dart';
import 'package:webview_flutter/webview_flutter.dart';

class Web extends StatefulWidget {
  Web({this.title, this.url});

  String title;
  String url;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _WebView();
  }
}

class _WebView extends State<Web> {
  WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: new Text(widget.title),
      ),
      body: new WebView(
        initialUrl: widget.url,
        //JS执行模式 是否允许JS执行
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (controller) {
          _controller = controller;
        },
        onPageFinished: (url) {},
        navigationDelegate: (NavigationRequest request) async {
          //对于需要拦截的操作 做判断
          print("打开:" + request.url);
          print("即将打开 ${request.url}");
//          ||request.url.indexOf("taobao.com")>-1||request.url.indexOf("taobao.cn")>-1
          if (request.url.indexOf("detail.tmall.com") > -1) {
            ProductInfoModel productInfo =
                await HttpUrlProductDetails(context, request.url);
            print("product");

            ProductModel product = new ProductModel();
            product.productId = productInfo.productId;
            product.title = productInfo.title;
            product.type = productInfo.type;
            product.finalPrice = productInfo.finalPrice;
            product.originalPrice = productInfo.originalPrice;
            product.returnPrice = productInfo.returnPrice;
            Navigator.of(context).pushNamed("/product", arguments: product);
            //做拦截处理
            //pushto....
            return null;
          }

          //不需要拦截的操作
          return NavigationDecision.navigate;
        },
        javascriptChannels: <JavascriptChannel>[
          JavascriptChannel(
              name: "getToken",
              onMessageReceived: (JavascriptMessage message) {
                print("参数： ${message.message}");

                String callbackname = message.message; //实际应用中要通过map通过key获取
                print(callbackname);
                String data = "收到消息调用了";
                String script = "callJS('"+data+"')";
                print(script);
                _controller.evaluateJavascript(script);
              }),
        ].toSet(),
      ),
    );
  }
}
